package com.example.fuluchou.service.impl;

import com.example.fuluchou.common.errorcode.ServiceErrorCodeConstants;
import com.example.fuluchou.common.exception.ServiceException;
import com.example.fuluchou.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile){
        //创建目录
        File file =new File(localPath);
        if(!file.exists()) {
            file.mkdirs();//目标目录的前目录不存在时也会创建,mkdir则不会
        }
        //重命名，避免同名图片无法保存
        //pic.jpg->xxx.jpg
        String filename = multipartFile.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(
                filename.lastIndexOf('.'));
        filename = UUID.randomUUID()+suffix;
        //保存图片
        try {
            multipartFile.transferTo(new File(localPath+"/"+filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }
        return filename;
    }
}
